package com.siau.SevenBubble;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.igexin.sdk.PushManager;

import org.jetbrains.annotations.Nullable;

import hhm.android.account.CreateLibraryOneActivity;
import hhm.android.library.LogUtils;
import hhm.android.library.utils.BackListener;
import hhm.android.library.utils.DataStoreUtils;
import hhm.android.library.utils.OnMultiClickListener;
import siau.android.base.DialogUtilsKt;
import siau.android.base.HttpHelper;
import siau.android.base.SBApplication;
import siau.android.base.SBBaseActivity;
import siau.android.base.SystemUtil;
import siau.android.http.model.CidRequest;
import siau.android.http.model.DeviceModel;
import siau.android.http.model.SourceTypeModel;
import siau.android.http.model.SystemDataRequest;
import siau.android.library.KeyString;

import static siau.android.base.SBStaticKt.LOGIN_ROUTER;
import static siau.android.base.SBStaticKt.MAIN_ROUTER;
import static siau.android.base.SBStaticKt.WEBVIEW_ROUTER;

public class SplashActivity extends SBBaseActivity {

    private final SplashActivityKotlinHelper helper = new SplashActivityKotlinHelper();
    private SurfaceView svStart;
    private MediaPlayer player;
    private SurfaceHolder holder;
    private AMapLocationClient mLocationClient;
    private TextView jump;
    private boolean end = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        SBApplication.Companion.setVersion(BuildConfig.VERSION_NAME);

        svStart = new SurfaceView(SBApplication.applicationContext);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        svStart.setLayoutParams(params);
        svStart.setVisibility(View.GONE);
        svStart.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        ((RelativeLayout) findViewById(R.id.activity_splash_rl)).addView(svStart, 0);

        jump = findViewById(R.id.activity_splash_junp);

        holder = svStart.getHolder();
        holder.addCallback(holderCallBack);
        holder.setKeepScreenOn(true);
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        ViewGroup.LayoutParams layoutParams = svStart.getLayoutParams();
        layoutParams.height = width / 9 * 16;
        layoutParams.width = width;
        svStart.setLayoutParams(layoutParams);

        LogUtils.Companion.setDebug(BuildConfig.DEBUG);
        helper.readBooleanFromDataStore(KeyString.notFirst, notFirst -> {
            if (notFirst) {
                getLocation();
            } else {
                DialogUtilsKt.getFirstOpenDialog(SplashActivity.this, new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        ARouter.getInstance().build(WEBVIEW_ROUTER).withString(KeyString.url, SBApplication.privacyString).navigation();
                    }
                }, new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        ARouter.getInstance().build(WEBVIEW_ROUTER).withString(KeyString.url, SBApplication.usaString).navigation();
                    }
                }, new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        storeAndGetLocation();
                    }
                }, new OnMultiClickListener() {
                    @Override
                    public void onMultiClick(View v) {
                        finish();
                    }
                });
            }
        });
    }

    private void storeAndGetLocation() {
        helper.writeBooleanToDataStore(KeyString.notFirst, true);
        getLocation();
    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(SBApplication.instance);
        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(aMapLocation -> {
            if (aMapLocation != null) {

                mLocationClient.stopLocation();
                mLocationClient.onDestroy();
                mLocationClient = null;

                helper.readStringFromDataStore(DataStoreUtils.INSTANCE.getTOKEN(), token -> {
                    KeyString.token = token;

                    //检查并提交下载来源
                    updateDownLoadData();

                    if (aMapLocation.getErrorCode() == 0) {

                        SBApplication.Companion.setLongitude(String.valueOf(aMapLocation.getLongitude()));
                        SBApplication.Companion.setLatitude(String.valueOf(aMapLocation.getLatitude()));

                        if (!TextUtils.isEmpty(token)) {
                            updateToken();
                        } else {
                            startMp4(() -> {
                                ARouter.getInstance().build(LOGIN_ROUTER).navigation();
                            });
                        }

                    } else {
                        SBApplication.Companion.setLongitude("");
                        SBApplication.Companion.setLatitude("");

                        if (!TextUtils.isEmpty(token)) {
                            updateToken();
                        } else {
                            startMp4(() -> {
                                ARouter.getInstance().build(LOGIN_ROUTER).navigation();
                            });
                        }
                    }
                });
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位一次
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void updateDownLoadData() {
        helper.readBooleanFromDataStore(KeyString.hasFirstUpLoad, hasFirstUpLoad -> {
            if (!hasFirstUpLoad) {
                SourceTypeModel model = new SourceTypeModel(BuildConfig.DOWNLOAD_FROM);
                new HttpHelper().downloadResource(model).subscribe(o -> storageDownloadFrom(), throwable -> {
                });
            }
        });
    }

    private void storageDownloadFrom() {
        runOnUiThread(() -> helper.writeBooleanToDataStore(KeyString.hasFirstUpLoad, true));
    }

    private void updateToken() {
        SystemDataRequest request = new SystemDataRequest(SystemUtil.getAndroidSystem(), "", SystemUtil.getSystemModel(), SystemUtil.getSystemVersion(), SBApplication.Companion.getLongitude(), SBApplication.Companion.getLatitude());
        new HttpHelper().refreshToken(request).subscribe(loginResponse -> {
            KeyString.token = loginResponse.getToken();
            helper.writeStringToDataStore(DataStoreUtils.INSTANCE.getTOKEN(), loginResponse.getToken());

            if (!TextUtils.isEmpty(SBApplication.cid) && !TextUtils.isEmpty(KeyString.token)) {
                CidRequest cidRequest = new CidRequest(SBApplication.cid);
                new HttpHelper().updateCid(cidRequest).subscribe(o -> {
                }, throwable -> {
                });
            }
            switch (loginResponse.getUserStatus()) {
                case 1://正常
                case 3://正常
                    getDefaultFamily();
                    break;
                case 2://待添加家庭
                    startMp4(() -> startActivity(new Intent(SplashActivity.this, CreateLibraryOneActivity.class)));
                    break;
            }
        }, throwable -> {
            startMp4(() -> {
                helper.writeStringToDataStore(DataStoreUtils.INSTANCE.getTOKEN(), "");
                KeyString.token = "";
                SBApplication.Companion.setRefreshMainActivityUI(false);
                SBApplication.Companion.setBecomeCreator(false);
                SBApplication.Companion.setCommunityChildId(-1);
                ARouter.getInstance().build(LOGIN_ROUTER).navigation();
            });
        });
    }

    private void getDefaultFamily() {
        new HttpHelper().getDefaultFamily().subscribe(getDefaultFamilyResponse -> {
            SBApplication.Companion.setUserData(getDefaultFamilyResponse);
            SBApplication.Companion.setHasWeightMachine(false);
            SBApplication.Companion.setHasHeightMachine(false);
            SBApplication.Companion.setHasToothBrushMachine(false);
            for (int i = 0; i < getDefaultFamilyResponse.getDeviceList().size(); i++) {
                DeviceModel d = getDefaultFamilyResponse.getDeviceList().get(i);
                if (d.getDeviceType() == 1) {
                    SBApplication.Companion.setHasWeightMachine(true);
                } else if (d.getDeviceType() == 2) {
                    SBApplication.Companion.setHasHeightMachine(true);
                } else if (d.getDeviceType() == 3) {
                    SBApplication.Companion.setHasToothBrushMachine(true);
                }
            }
            PushManager.getInstance().bindAlias(SplashActivity.this, SBApplication.userData.getUserAlias());
            helper.writeStringToDataStore(KeyString.userAlias, SBApplication.userData.getUserAlias());

            startMp4(() -> {
                //从外部H5跳进来 SchemeActivity传入参数
                String data = getIntent().getStringExtra(KeyString.data);
                if (!TextUtils.isEmpty(data)) {
                    ARouter.getInstance().build(MAIN_ROUTER).withString(KeyString.data, data).withString(KeyString.H5Type, getIntent().getStringExtra(KeyString.H5Type)).navigation();
                } else {
                    ARouter.getInstance().build(MAIN_ROUTER).navigation();
                }
            });
        }, throwable -> startMp4(() -> {
            helper.writeStringToDataStore(DataStoreUtils.INSTANCE.getTOKEN(), "");
            KeyString.token = "";
            SBApplication.Companion.setRefreshMainActivityUI(false);
            SBApplication.Companion.setBecomeCreator(false);
            SBApplication.Companion.setCommunityChildId(-1);
            ARouter.getInstance().build(LOGIN_ROUTER).navigation();
        }));
    }

    private void startMp4(BackListener listener) {
        player.setOnPreparedListener(mp -> {
            if (!player.isPlaying()) {
                svStart.setVisibility(View.VISIBLE);
                player.start();
            }
        });
        try {
            AssetFileDescriptor file = null;
            int index = 0;
            while (file == null) {
                file = getResources().openRawResourceFd(R.raw.splash);
                if (index == 10) {
                    listener.callBack();
                    finish();
                }
                index++;
                LogUtils.Companion.e("hhm", "hhm--->start video index  ---  " + index);
            }
            player.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
            player.setLooping(false);
            jump.setVisibility(View.VISIBLE);
            player.setOnInfoListener((mp, what, extra) -> {
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    svStart.setBackgroundColor(Color.TRANSPARENT);
                }
                return true;
            });
            jump.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View v) {
                    if (!end) {
                        end = true;
                        listener.callBack();
                        player.stop();
                        finish();
                    }
                }
            });
            player.setOnCompletionListener(mp -> {
                if (!end) {
                    end = true;
                    listener.callBack();
                    finish();
                }
            });
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        if (player.isPlaying()) {
            player.stop();
        }
        player.reset();
        player.release();
        player = null;
        holder.removeCallback(holderCallBack);
        holder.getSurface().release();
        holder = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        ((RelativeLayout) findViewById(R.id.activity_splash_rl)).removeView(svStart);
        super.onDestroy();
    }

    private final SurfaceHolder.Callback holderCallBack = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            player.setDisplay(holder);
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

        }
    };
}
